<template lang="pug">
  div(v-loading="loading")
    el-card.commonCard(shadow="never")
      h2.title
        span {{babyBaseInfo.name}}
        el-button.save(type="primary" size="small" @click="submitHandle" v-if="!id") 保存
      .detail
        p
          span 性别: {{dictFilter(babyBaseInfo.gender, 'sex')}}
          span 出生日期: {{babyBaseInfo.birthday | dateFilter}}
          span 出生体重: {{babyBaseInfo.weight}}kg
          span 出生身长: {{babyBaseInfo.height}}cm
      form-box(
        ref="basicForm"
        :fields="basicFormFields"
        :showBtns="false"
        size="mini"
        labelWidth="80px"
        :formProps="{ inline: true, disabled: !!id }"
      )
      #echartsBox(style="height: 436px;margin: 32px 0 72px" v-if="beforeId")
      el-form(ref="form" :model="formData" :rules="rules" label-width="136px" size="mini" :disabled="!!id")
        section.panel(v-for="(panel, index) in formItems" :key="index")
          h3
            el-divider(content-position="left") {{panel.title}}
          .panelForm
            el-row(:gutter="12" v-if="panel.list || fieldsObj[panel.key]")
              el-col(
                v-for="item in (panel.list || fieldsObj[panel.key])"
                :key="item.key"
                :span="panel.span || item.span || 12"
              )
                el-form-item(:label="item.label" :prop="item.key" :label-width="item.labelWidth")
                  el-input(v-if="item.type === 'input'" v-model="formData[item.key]")
                  el-input(v-else-if="item.type === 'textarea'" rows="4" type="textarea" v-model="formData[item.key]")
                  template(v-else-if="item.type === 'number'")
                    el-input-number(v-model="formData[item.key]" :min="0" @change="val => formChange(val, item.key)" style="width: 108px")
                    small.ml5(v-if="item.unit") {{item.unit}}
                  el-time-picker(
                    v-else-if="item.type === 'time'"
                    v-model="formData[item.key]"
                    :picker-options="{start: '05:30',step: '00:15',end: '23:30'}"
                  )
                  div(v-else :class="{radioBox: !item.options}")
                    el-radio-group(v-model="formData[item.key]" :disabled="!!item.disabled")
                      el-radio-button(v-for="opt in options[item.options || 'commonly']" :key="opt.value" :label="opt.value") {{opt.label}}
                    el-input(v-if="formData[item.key] === '其他'" v-model="formData[`other-${item.key}`]" placeholder="请输入")
            el-form-item(v-if="panel.slot")
              el-button(type="success" size="mini" @click="() => addItem(panel.key, panel.title)" v-if="!id") 增加
      BackToTop
</template>
<script>
import dayjs from 'dayjs'
import isEmpty from 'lodash/isEmpty'
import echartsMixin from '@/components/Basic/Charts/mixins/resize'
import dictMixin from '@/mixins/dict'
import BackToTop from '@/components/Basic/BackToTop'
import { getChildrenDetail } from '@/api/common'
import { toChinesNum } from '@/utils/util'
import { getGrowEvaluatescale, childrenHealthSubmit, getChildrenHealthDetail } from './api'
import { basicFormFields, formItems, options } from './config'

const formData = {}
const rules = {}
formItems.forEach(item => {
  if (Array.isArray(item.list)) {
    item.list.forEach(x => {
      formData[x.key] = ''
      if (x.required) {
        rules[x.key] = [{ required: true, message: `请${!x.type ? '选择' : '输入'}${x.label}` }]
      }
      if (!x.type && !x.options) {
        formData[`other-${x.key}`] = ''
      }
    })
  }
})

export default {
  components: {
    BackToTop
  },
  mixins: [dictMixin, echartsMixin],
  data () {
    return {
      loading: false,
      info: {}, // 本次评测详情
      beforeInfo: {}, // 上次评测详情
      babyBaseInfo: {}, // 宝宝基本信息
      echartsId: 'echartsBox',
      formItems,
      options,
      formData: {},
      rules,
      // 可以手动添加得
      fieldsObj: {
        parentsAttentionQuestion: [],
        healthGuide: []
      }
    }
  },
  computed: {
    // 查看详情会携带id
    id () {
      return this.$route.query.id
    },
    beforeId () {
      return this.$route.query.beforeId
    },
    childrenId () {
      return this.$route.query.childrenId
    },
    basicFormFields () {
      const { info } = this
      return basicFormFields(info)
    }
  },
  watch: {
    childrenId: {
      handler (val) {
        if (val) {
          this.getChildrenDetail()
        }
      },
      immediate: true
    },
    id: {
      handler (val) {
        if (val) {
          this.getEvaluteDetail(val)
        }
      },
      immediate: true
    }
  },
  created () {
  },
  methods: {
    // 获取评测详情
    getEvaluteDetail (id, type = '') {
      this.loading = true
      getChildrenHealthDetail({ id }).then(res => {
        const healthBaseInfo = res?.healthBaseInfo || {}
        this[type ? `${type}Info` : 'info'] = healthBaseInfo
        if (!type) {
          // 保存宝宝信息
          if (isEmpty(this.babyBaseInfo)) {
            this.babyBaseInfo = res?.children || {}
          }
          for (const key in formData) {
            if (healthBaseInfo[key]) {
              // 判断其他得输入
              if (key.startsWith('other-')) {
                const key1 = key.split('-')[1]
                if (['正常', '不正常'].includes(healthBaseInfo[key1])) {
                  formData[key1] = '其他'
                }
              }
              if (['routineWakeUpTime', 'routineSleepInertia'].includes(key)) {
                formData[key] = new Date(`2021-09-01 ${healthBaseInfo[key]}`).getTime()
              } else {
                formData[key] = healthBaseInfo[key]
              }
            }
          }
          this.formData = { ...formData }

          // 初始化生长发育评价
          if (healthBaseInfo.physicalHeight && !healthBaseInfo.growEvaluateHeightScale) {
            this.formChange(healthBaseInfo.physicalHeight, 'physicalHeight')
          }
          if (healthBaseInfo.physicalWeight && !healthBaseInfo.growEvaluateWeightScale) {
            this.formChange(healthBaseInfo.physicalWeight, 'physicalWeight')
          }

          // 初始化父母关注问题和保健指导列表
          const parentsAttentionQuestions = Object.keys(healthBaseInfo || {}).filter(x => x.startsWith('parentsAttentionQuestion'))
          const healthGuides = Object.keys(healthBaseInfo || {}).filter(x => x.startsWith('healthGuide'))
          parentsAttentionQuestions.map(x => {
            this.addItem('parentsAttentionQuestion', '父母关注的问题')
          })
          healthGuides.map(x => {
            this.addItem('healthGuide', '保健指导')
          })
        }
      }).finally(() => {
        if (this.beforeId && !type) {
          this.getEvaluteDetail(this.beforeId, 'before')
        }
        if (type === 'before') {
          this.getEcharts()
        }
        this.loading = false
      })
    },
    // 新增得时候获取宝宝信息
    getChildrenDetail () {
      this.loading = true
      getChildrenDetail({ childrenId: this.childrenId }).then(res => {
        this.babyBaseInfo = {
          ...res?.children
        }
        this.addItem('parentsAttentionQuestion', '父母关注的问题')
        this.addItem('healthGuide', '保健指导')
      }).finally(() => {
        this.loading = false
      })
    },
    // 表单改变
    async formChange (value, key) {
      const { formData, childrenId, babyBaseInfo } = this
      if (['physicalWeight', 'physicalHeight'].includes(key)) {
        // 获取生长发育评价
        const data = await getGrowEvaluatescale({
          childrenId: childrenId || babyBaseInfo.id,
          height: key === 'physicalHeight' ? value : formData.physicalHeight,
          weight: key === 'physicalWeight' ? value : formData.physicalWeight
        })
        if (data?.wResult) formData.growEvaluateWeightScale = data?.wResult
        if (data?.hResult) formData.growEvaluateHeightScale = data?.hResult
        this.formData = { ...formData }
      }
    },
    // 新增问题或者指导
    addItem (type, title) {
      const { fieldsObj, formData, info } = this
      const key = `${type}${fieldsObj[type].length + 1}`
      fieldsObj[type].push({
        label: `${title.substring(title.length - 2)}${toChinesNum(fieldsObj[type].length + 1)}`,
        key,
        type: 'textarea',
        span: 24
      })
      this.formData = { ...formData, [key]: info[key] || '' }
      this.fieldsObj = { ...fieldsObj }
    },
    // 保存
    async submitHandle () {
      const { formData, rules, $message, childrenId } = this
      const basicValue = await this.$refs.basicForm.submitForm()
      this.$refs.form.validate(valid => {
        if (valid) {
          const params = {
            childrenId,
            ...basicValue,
            ...formData
          }

          // 格式化下时间
          if (params.routineWakeUpTime) {
            params.routineWakeUpTime = dayjs(new Date(formData.routineWakeUpTime)).format('HH:mm:ss')
          }

          if (params.routineSleepInertia) {
            params.routineSleepInertia = dayjs(new Date(formData.routineSleepInertia)).format('HH:mm:ss')
          }

          for (const key in params) {
            if (key.startsWith('other-')) {
              params[key.split('-')[1]] = params[key]
            }
          }

          childrenHealthSubmit(params).then(res => {
            $message.success('保存成功')
            this.$router.go(-1)
          })
        } else {
          for (const key in rules) {
            if (!formData[key]) {
              $message.error(rules[key][0].message)
              return
            }
          }
        }
      })
    },
    getEcharts () {
      const { beforeInfo, info } = this
      let val1 = []
      let val2 = []
      const feilds = ['physicalHeight', 'physicalWeight', 'physicalHeader', 'physicalCircumference', 'physicalBregma']
      function numFormat (index, flag) {
        if (flag) {
          return (info && info[feilds[index]]) ? info[feilds[index]] : 0
        } else {
          return (beforeInfo && beforeInfo[feilds[index]]) ? beforeInfo[feilds[index]] : 0
        }
      }
      val1 = [numFormat(0, true), numFormat(1, true), numFormat(2, true), numFormat(3, true), numFormat(4, true)]
      val2 = [numFormat(0, false), numFormat(1, false), numFormat(2, false), numFormat(3, false), numFormat(4, false)]
      const options = {
        legend: {
          data: ['上次测评', '本次测评']
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        tooltip: {
          trigger: 'axis',
          formatter: (params) => {
            let tip = ''
            params.map((x, index) => {
              const unit = params[index].dataIndex === 1 ? 'KG' : 'CM'
              if (index === 0) {
                tip += params[0].axisValue + '</br>'
              }
              tip += params[index].marker + '<span>' + params[index].seriesName + ':' + params[index].value + unit + '</span></br>'
            })
            return tip
          },
          axisPointer: {
            type: 'shadow'
          }
        },
        xAxis: {
          type: 'category',
          data: ['身高', '体重', '头围', '胸围', '前囟']
        },
        yAxis: {
          type: 'value',
          boundaryGap: [0, 0.01]
        },
        series: [
          {
            name: '本次测评',
            type: 'bar',
            data: val1,
            itemStyle: {
              color: '#6f7ee1'
            },
            label: {
              normal: {
                show: true,
                position: 'top',
                formatter: params => {
                  return params.value + (params.name === '体重' ? 'kg' : 'cm')
                }
              }
            }
          },
          {
            name: '上次测评',
            type: 'bar',
            data: val2,
            itemStyle: {
              color: '#aaaae6'
            },
            label: {
              normal: {
                show: true,
                position: 'top',
                formatter: params => {
                  return params.value + (params.name === '体重' ? 'kg' : 'cm')
                }
              }
            }
          }
        ]
      }
      this.$_chartMixin_init(options)
    }
  }
}
</script>
<style lang="scss" scoped>
h2.title{
  position: relative;

  span{
    background: $green;
    color: #fff;
    display: inline-block;
    font-weight: normal;
    padding: 0 32px 0 12px;
    height: 32px;
    line-height: 32px;
    font-size: 14.6px;
    border-bottom-right-radius: 16px;
    border-top-right-radius: 16px;
  }

  .save{
    position: absolute;
    right: 0;
    top: 0
  }
}
.detail{
  font-weight: normal;
  margin-bottom: 16px;

  p {
    margin-top: 10px
  }

  span {
    margin-right: 24px;
  }
}

.panel {
  h3 {
    .el-divider__text{
      font-weight: bold;
    }
  }
}

.commonCard {
  ::v-deep {
    .el-radio-button__orig-radio:disabled:checked + .el-radio-button__inner {
      background-color: $--color-primary;
      color: #fff
    }

    .is-disabled {
      .el-input__inner, .el-textarea__inner{
        background-color: #fff;
        color: $--color-text-regular
      }
    }
  }
}

.radioBox{
  display: flex;

  .el-radio-group{
    width: 182px
  }

  .el-input{
    flex: 1
  }

}

</style>
